﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Data .SqlClient ;
using Baimasoft.FrameWork.Base;
using Baimasoft.Manage.SqlServerDAL;
using HsTec.Mobile.Green.SqlServerDAL;

public partial class DocumentManage_Document_List : Baimasoft.Web.UI.PageManagerTop
{
    BaimasoftFile MyFile = new BaimasoftFile();
    DataFile datafile = new DataFile();

    HsTec.Mobile.Green.SqlServerDAL.DataFile mydatafile = new HsTec.Mobile.Green.SqlServerDAL.DataFile();
    HsTec.Mobile.Green.SqlServerDAL.DataFolder MyDF = new HsTec.Mobile.Green.SqlServerDAL.DataFolder();

    LogManage MyLog = new LogManage();

    Machineroom machineroom = new Machineroom();
    Network MyNt = new Network();
    Area area = new Area();
    Project project = new Project();
    public string sID = "-1";
    public string stype="1";    // 1 文档 2 项目 2区域 4 机房  5 网元

    protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Attributes.Add("onclick", "this.form.target='_blank'"); 

        this.BindControlEvent();
        this.HiddenID.Value = "";

        if (this.Request.Params["ID"] != null)
        {
            sID = this.Request.Params["ID"].Trim();            
            //ThisPageFolderID.Value = sID;
            stype = this.Request.Params["stype"].Trim(); 
        }
        else
        {
            sID = "-1";
        }
        if (!this.IsPostBack)
        {
            try
            {
                AspNetHelper.BtnGrantInfo(this);  //按钮控制

                ChoiceDt.Checked = true;
                ifChoiceDt.Style.Add("display", "");
                AllDt.Style.Add("display", "none");

                GridView1.Attributes.Add("BorderColor", "LightSkyBlue");
                this.SDT.Text = DateTime.Now.ToString("yyyy-MM") + "-01";
                this.EDT.Text = DateTime.Now.ToString("yyyy-MM-dd");
                ddlRegionDataBind();
                ddlMachineDataBind();
                ddlnetworkDataBind();
                ddlProjectDataBind();
                this.BindGridViewData();//绑定GridView,为删除服务
            }
            catch
            {
            }
        }
    }

    protected override void BindGridViewData()
    {
        this.DataSource = datafile.GetDataFileInfos (GetSearchString());
        this.DataSource.DefaultView.Sort = this.SortString;
        GridView1.DataSource = this.DataSource.DefaultView;
        GridView1.DataBind();
        KeepStyle();
    }

    /// <summary>
    /// 区域下拉框
    /// </summary>
    protected void ddlRegionDataBind()
    {
        ddlRegionid.DataSource = area.GetAreaInfos (string.Empty);
        ddlRegionid.DataBind();
        ddlRegionid.Items.Insert(0, "全部");
        ddlRegionid.Items[0].Value = "0";
    }

    /// <summary>
    /// 机房下拉框绑定
    /// </summary>
    protected void ddlMachineDataBind()
    {
        ddlMachineid.DataSource = machineroom.GetMachineRooms("");
        ddlMachineid.DataBind();
        ddlMachineid.Items.Insert(0, "全部");
        ddlMachineid.Items[0].Value = "0";
    }

    /// <summary>
    /// 网元下拉框绑定
    /// </summary>
    protected void ddlnetworkDataBind()
    {
        ddlnetwork.DataSource = MyNt.GetNetWorks ("");
        ddlnetwork.DataBind();
        ddlnetwork.Items.Insert(0, "全部");
        ddlnetwork.Items[0].Value = "0";
    }

    /// <summary>
    /// 项目下拉框
    /// </summary>
    protected void ddlProjectDataBind()
    {
        this.ddlProject.DataSource = project.GetProjectInfos ("");
        this.ddlProject.DataBind();
        this.ddlProject.Items.Insert(0, "全部");
        this.ddlProject.Items[0].Value = "0";
    }  

    protected override string GetSearchString()
    {
        string searchStr = string.Empty;
        searchStr += " ( 1=1) ";

        if (stype == "1")  //文档
        {
            if (ChoiceName_1.Value.ToString().Trim() != "")
            {
                if (HChoiceID_1.Value.ToString().Trim() != "")
                {
                    searchStr += " and a.FolderID in(" + HChoiceID_1.Value.ToString().Trim() + ") ";
                }
            }
            else
            {
                searchStr += " and ( a.FolderID = '" + sID + "') ";
            }
        }
        else if (stype == "2")  //项目
        {
            searchStr += " and ( a.Project = '" + sID + "') ";
        }


        if (this.Name.Text.Trim().Length > 0)
        {
            searchStr += " and a.Name like '%" + this.Name.Text.ToString().Trim() + "%' ";
        }

        if (this.KeyWord.Text.Trim().Length > 0)
        {
            searchStr += " and a.KeyWord like '%" + this.KeyWord.ToString().Trim() + "%' ";
        }

        if (ChoiceDt.Checked == true)
        {
            if (this.SDT.Text.ToString().Trim() != "")
            {
                searchStr += " and convert(varchar(10),a.CreatDT,120) >= '" + this.SDT.Text.ToString().Trim() + "' ";
            }
            else
            {
                searchStr += " and convert(varchar(10),a.CreatDT,120) >= '" + DateTime.Now.ToString("yyyy-MM-dd") + "' ";
            }
            if (this.EDT.Text.ToString().Trim() != "")
            {
                searchStr += " and convert(varchar(10),a.CreatDT,120) <= '" + this.EDT.Text.ToString().Trim() + "' ";
            }
            else
            {
                searchStr += " and convert(varchar(10),a.CreatDT,120) <= '" + DateTime.Now.ToString("yyyy-MM-dd") + "' ";
            }
        }

        string sddlRegionid = ddlRegionid.SelectedValue.ToString().Trim();
        if (sddlRegionid != "0")
        {
            searchStr += " and a.Region ='" + sddlRegionid + "' ";
        }
        if (ddlMachineid.SelectedValue.ToString().Trim() != "0")
        {
            searchStr += " and a.MachineRoom ='" + ddlMachineid.SelectedValue.ToString().Trim() + "' ";
        }
        if (ddlnetwork.SelectedValue.ToString().Trim() != "0")
        {
            searchStr += " and a.NetWork ='" + ddlnetwork.SelectedValue.ToString().Trim() + "' ";
        }
        if (ddlProject.SelectedValue.ToString().Trim() != "0")
        {
            searchStr += " and a.Project ='" + ddlProject.SelectedValue.ToString().Trim() + "' ";
        }

        //取该用户数据角色授权信息
        string sChoiceFolderCol = AspNetHelper.GetRightFolderIDCol();
        string sChoiceFileCol = AspNetHelper.GetRightFileIDCol();

        if ((sChoiceFolderCol.Trim() == "0" || sChoiceFolderCol.Length == 0) && (sChoiceFileCol.Trim() == "0" || sChoiceFileCol.Length == 0))
        { //没有授权的情况下
            //searchStr += " and  ( 1<>1 )";
        }
        else
        {
            if (sChoiceFolderCol.Trim() != "0" && sChoiceFolderCol.Length > 0)
            {
                string sFolderIDCols = MyDF.GetFolderChildIDCols(sChoiceFolderCol.Trim());
                if (sFolderIDCols != "")
                {
                    searchStr += " and a.FolderID in(" + sFolderIDCols + ") ";
                }
            }

            if (sChoiceFileCol.Trim() != "0" && sChoiceFileCol.Length > 0)
            {
                //自己的文档自己可以查看
                string sLogonID = Session["Baimasoft_User_LogonID"].ToString();
                if (sLogonID == "")
                {
                    sLogonID = "0";
                }

                if (sLogonID.ToUpper() != "ADMIN")
                {
                    searchStr += "  and (a.ID in(" + sChoiceFileCol + ") or a.creatrole = '" + sLogonID + "' )  ";
                }
                else
                {
                    searchStr += " and a.ID in(" + sChoiceFileCol + ") ";
                }
                //
            }
        }

        searchStr += " order by a.name, versionnumber desc ";

        return searchStr;
    }

    protected void BtnRefresh1_Click(object sender, EventArgs e)
    {
        this.DataSource = datafile.GetDataFileInfos(GetSearchString());
        this.DataSource.DefaultView.Sort = this.SortString;
        GridView1.DataSource = this.DataSource.DefaultView;
        GridView1.DataBind();
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        string strings = "";
        try
        {
            string ThisRoleCode = (string)Session["Baimasoft_Role_Code"];
            string sLogon = (string)Session["Baimasoft_User_LogonID"];
            string sTempFileExtension = mydatafile.GetMyFileExtension (ThisRoleCode);

            if (e.CommandName == "Down")
            {
                int index = Convert.ToInt32(e.CommandArgument);

                GridViewRow selectedRow = GridView1.Rows[index];

                TableCell contactFE = selectedRow.Cells[9];  //AliasName
                string sFileExtension = contactFE.Text.ToString ().Trim ();
                string[] aTempFE = sTempFileExtension.Split(',');
                string sFlag = "0";
                for (int j = 0; j < aTempFE.Length; j++)
                {
                    if (sFileExtension == aTempFE[j].ToString().Trim())
                    {
                        sFlag = "1";
                        break;
                    }
                }
                if (sFlag == "0" && sLogon.ToLower () != "admin")
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('您无权下载" + sFileExtension + "格式文档！');</script>");
                    return;
                }
                else
                {

                    string sTempPath = "";
                    TableCell contactID = selectedRow.Cells[1]; //ID
                    string FileID = contactID.Text;

                    SqlDataReader MySDR = mydatafile.ReadDataFileInfo("a.id =" + FileID);
                    if (MySDR.Read())
                    {
                        sTempPath = MySDR["path"].ToString().Trim();
                    }

                    TableCell TrueFileName = selectedRow.Cells[2];  //Name
                    string sTrueFileName = TrueFileName.Text;

                    TableCell contactName = selectedRow.Cells[3];  //AliasName
                    string FileName = contactName.Text;
                    string FilePath, InFile;
                    string m_Root = ConfigurationManager.AppSettings["DocumentMange"];  //取Web.Config文件中的配置信息,在配置的时候要注意该盘权限
                    FilePath = m_Root + sTempPath + "\\" + FileName;                    //写到服务器上的路径

                    //ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + str + "');</script>");
                    InFile = FilePath;
                    //--------------------------
                    int Index;
                    Index = FilePath.Trim().Length - FileName.Length;
                    string OutFile;
                    OutFile = FilePath.Remove(Index, FileName.Length);

                    OutFile += "!" + FileName;
                    string sEncryptFile = ConfigurationManager.AppSettings["EncryptFile"];

                    MyFile.DecryptFile(InFile, OutFile, sEncryptFile); //对文件进行加密处理

                    //Response.Clear();
                    //Response.ClearContent();
                    //Response.ClearHeaders();
                    //Response.Buffer = false;
                    ////Response.Charset = "utf-8";
                    //Response.HeaderEncoding = System.Text.Encoding.GetEncoding("gb2312"); 
                    ////this.EnableViewState = false;
                    ////Response.ContentEncoding = System.Text.Encoding.UTF8;
                    //Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                    ////Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(sTrueFileName)));
                    //string sfileNameEncode = HttpUtility.UrlEncode (sTrueFileName).ToString();
                    //Response.AppendHeader("Content-Disposition", "attachment;filename=" + sfileNameEncode);
                    //Response.AddHeader("Content-Length", sfileNameEncode.Length .ToString ());
                    //Response.ContentType = "application/octet-stream"; 
                    //Response.WriteFile(OutFile);
                    //Response.Flush();
                    //Response.Close();


                    Response.Clear();
                    Response.ClearHeaders();
                    Response.Charset = "utf-8";
                    Response.Buffer = false;
                    this.EnableViewState = false;
                    Response.ContentEncoding = System.Text.Encoding.UTF8;
                    Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(sTrueFileName)));
                    Response.WriteFile(OutFile);
                    Response.Flush();
                    Response.Close();

                    MyFile.DeleteFile(OutFile);//删除临时文件
                    Response.End();

                    try
                    {
                        string sPerID = (string)Session["Baimasoft_Pers_ID"];
                        string sContent = "用户" + (string)Session["Baimasoft_User_LogonID"] + "下载文件：" + OutFile;
                        string sIP = Page.Request.UserHostAddress;
                        MyLog.InsertLog("3", sPerID, sContent, sIP);
                    }
                    catch
                    {
                        string sPerID = "0";
                        string sContent = "下载文件：" + OutFile;
                        string sIP = Page.Request.UserHostAddress;
                        MyLog.InsertLog("3", sPerID, sContent, sIP);
                    }
                }
            }
            else if (e.CommandName == "Open")
            {
                int index = Convert.ToInt32(e.CommandArgument);

                GridViewRow selectedRow = GridView1.Rows[index];

                TableCell contactFE = selectedRow.Cells[9];  //AliasName
                string sFileExtension = contactFE.Text.ToString ().Trim ();
                string[] aTempFE = sTempFileExtension.Split(',');
                string sFlag = "0";
                for (int j = 0; j < aTempFE.Length; j++)
                {
                    if (sFileExtension == aTempFE[j].ToString().Trim())
                    {
                        sFlag = "1";
                        break;
                    }
                }
                if (sFlag == "0" && sLogon.ToLower () != "admin")
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('您无权打开" + sFileExtension + "格式文档！');</script>");
                    return;
                }
                else
                {
                    string sReadFilePath = ConfigurationManager.AppSettings["ReadFilePath"];

                    //删除指定文件夹下面的所有文件和文件夹
                    if (Directory.Exists(sReadFilePath))
                    {
                        foreach (string d in Directory.GetFileSystemEntries(sReadFilePath))
                        {
                            if (File.Exists(d))
                                File.Delete(d); //直接删除其中的文件                           
                            else
                                Directory.Delete(d); //递归删除子文件夹    
                        }
                    }

                    string sTempPath = "";
                    TableCell contactID = selectedRow.Cells[1]; //ID
                    string FileID = contactID.Text;

                    SqlDataReader MySDR = mydatafile.ReadDataFileInfo("a.id =" + FileID);
                    if (MySDR.Read())
                    {
                        sTempPath = MySDR["path"].ToString().Trim();
                    }

                    TableCell TrueFileName = selectedRow.Cells[2];  //Name
                    string sTrueFileName = TrueFileName.Text;

                    TableCell contactName = selectedRow.Cells[3];  //AliasName
                    string FileName = contactName.Text;
                    string FilePath, InFile;
                    string m_Root = ConfigurationManager.AppSettings["DocumentMange"];  //取Web.Config文件中的配置信息,在配置的时候要注意该盘权限
                    FilePath = m_Root + sTempPath + "\\" + FileName;                    //写到服务器上的路径

                    //ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + str + "');</script>");
                    InFile = FilePath;
                    //--------------------------
                    int Index;
                    Index = FilePath.Trim().Length - FileName.Length;

                    string OutFile;
                    //OutFile = FilePath.Remove(Index, FileName.Length);

                    OutFile = sReadFilePath + "\\!" + FileName;
                    string sEncryptFile = ConfigurationManager.AppSettings["EncryptFile"];

                    MyFile.DecryptFile(InFile, OutFile, sEncryptFile); //对文件进行加密处理

                    Response.Redirect("ReadFile/!" + FileName);
                    Response.Flush();
                    Response.Close();
                    Response.End();

                    try
                    {
                        string sPerID = (string)Session["Baimasoft_Pers_ID"];
                        string sContent = "用户" + (string)Session["Baimasoft_User_LogonID"] + "打开文件：" + InFile;
                        string sIP = Page.Request.UserHostAddress;
                        MyLog.InsertLog("3", sPerID, sContent, sIP);
                    }
                    catch
                    {
                        string sPerID = "0";
                        string sContent = "打开文件：" + InFile;
                        string sIP = Page.Request.UserHostAddress;
                        MyLog.InsertLog("3", sPerID, sContent, sIP);
                    }
                }
            }
        }
        catch
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('文件下载失败！请与系统管理人员联系！');</script>");
            return;
        }
    }

    /// <summary>
    /// 全选
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnAll_Click(object sender, EventArgs e)
    {
        HtmlInputCheckBox chk;
        string sTemp = "";
        if (hidAll.Value == "1")
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                chk = (HtmlInputCheckBox)(GridView1.Rows[i].Cells[0].FindControl("OneCheck"));
                chk.Checked = true;
                sTemp += chk.Value + "|";
            }
            ChoiceInfo.Value = ChoiceInfo.Value + sTemp;
        }
        else
        {
            string sTempNo = "";
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                chk = (HtmlInputCheckBox)(GridView1.Rows[i].Cells[0].FindControl("OneCheck"));
                chk.Checked = false;
                sTempNo += chk.Value + "|";
            }
            ChoiceInfo.Value = ChoiceInfo.Value.Replace(sTempNo, "");
        }
    }

    protected new void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            HtmlInputCheckBox Chk = (HtmlInputCheckBox)(e.Row.Cells[0].FindControl("OneCheck"));
            if (ChoiceInfo.Value.IndexOf(e.Row.Cells[1].Text.Trim()) >= 0)
            {
                HtmlInputCheckBox ChkSelected = (HtmlInputCheckBox)(e.Row.Cells[0].FindControl("OneCheck"));
                ChkSelected.Checked = true;
            }

            if (e.Row.RowIndex % 2 != 0)
            {
                e.Row.Attributes.Add("onclick", "tog(this,'#EFEFF8')");
            }
            else
            {
                e.Row.Attributes.Add("onclick", "tog(this,'#F9F9FB')");
            }
        }
    }

    protected void ddlRegionid_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sddlRegion = ddlRegionid.SelectedValue.ToString().Trim();

        DataTable dt1 = machineroom.GetMachineRooms ("a.region_id='" + sddlRegion + "'");
        this.ddlMachineid.DataValueField = "mroom_id";
        this.ddlMachineid.DataTextField = "mroom_name";
        this.ddlMachineid.DataSource = dt1;
        this.ddlMachineid.DataBind();

        string sddlMachine = ddlMachineid.SelectedValue.ToString().Trim();
        DataTable dt2 = MyNt.GetNetWorks ("a.mroom_id = '" + sddlMachine + "'");
        this.ddlnetwork.DataValueField = "netw_id";
        this.ddlnetwork.DataTextField = "netw_name";
        this.ddlnetwork.DataSource = dt2;
        this.ddlnetwork.DataBind();
        KeepStyle();
    }
    protected void ddlMachineid_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sddlMachine = ddlMachineid.SelectedValue.ToString().Trim();
        DataTable dt2 = MyNt.GetNetWorks ("a.mroom_id = '" + sddlMachine + "'");
        this.ddlnetwork.DataValueField = "netw_id";
        this.ddlnetwork.DataTextField = "netw_name";
        this.ddlnetwork.DataSource = dt2;
        this.ddlnetwork.DataBind();
        KeepStyle();
    }

    /// <summary>
    /// 保存相应的状态
    /// </summary>
    protected void KeepStyle()
    {
        if (ChoiceDt.Checked == true)
        {
            ifChoiceDt.Style.Add("display", "");
            AllDt.Style.Add("display", "none");
            LDt.Value = "";
        }
        else
        {
            ifChoiceDt.Style.Add("display", "none");
            AllDt.Style.Add("display", "");
            LDt.Value = "全部日期";
        }
    }

}